import cv2
import pyzbar.pyzbar as pyzbar
import json
import qrcode


class Barcode(object):
    flag = 0

    def get_barcode(self):
        camera = cv2.VideoCapture(0)

        while True:
            # 读取当前帧
            ret, frame = camera.read()
            # 转为灰度图像
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            # data = "，"
            # gray = qrcode.make(data=data)
            py_barcode = pyzbar.decode(gray)
            if py_barcode:
                self.flag += 1

            cv2.waitKey(5)
            cv2.imshow("camera", frame)
            if self.flag == 3:
                camera.release()
                cv2.destroyAllWindows()
                self.flag = 0
                return py_barcode

    def barcode_decode(self):
        bar = self.get_barcode()
        bar_str = bar[0].data.decode('utf-8')
        return bar_str

    def str_to_json(self):
        bar = self.barcode_decode()
        dic = {}
        bar = bar.strip('{')
        bar = bar.strip('}')
        bar = bar.split(',')
        for i in bar:
            lis = i.split(':')
            dic[lis[0]] = lis[1]
        return json.dumps(dic)


if __name__ == '__main__':
    barcode = Barcode()
    my_barcode = barcode.str_to_json()
    bar_dic = json.loads(my_barcode)
    print(bar_dic['pc'])

    # dic = {}
    # str1 = '{pbn:PICK20032810007,on:SO2003280797,pc:C25612,pm:0805W8J0103T5E,qty:100,mc:null,cc:1}
    # print(dic)
